package com.jvtd.eyl.ui.main.home.periodicalInfo;

import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jakewharton.rxbinding2.view.RxView;
import com.jvtd.eventBus.EventCenter;
import com.jvtd.eyl.R;
import com.jvtd.eyl.base.BaseMvpActivity;
import com.jvtd.eyl.bean.binding.BookBean;
import com.jvtd.eyl.bean.binding.PeriodicalBean;
import com.jvtd.eyl.bean.http.TimeBean;
import com.jvtd.eyl.bean.ui.SortsBean;
import com.jvtd.eyl.constants.EventCode;
import com.jvtd.eyl.databinding.ActivityPeriodicalInfoBinding;
import com.jvtd.eyl.utils.AppIndicatorUtils;
import com.jvtd.eyl.widget.EditorView;
import com.jvtd.eyl.widget.TriangleDrawable;
import com.jvtd.utils.MagicIndicatorUtils;
import com.jvtd.utils.SmartRefreshUtils;
import com.jvtd.utils.UiUtils;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zyyoona7.popup.EasyPopup;
import com.zyyoona7.popup.XGravity;
import com.zyyoona7.popup.YGravity;

import net.lucode.hackware.magicindicator.FragmentContainerHelper;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

/**
 * 期刊详情
 * <p>
 * 作者:chenlei
 * 时间:2018/11/14 9:18 AM
 */
public class PeriodicalInfoActivity extends BaseMvpActivity implements PeriodicalInfoMvpView, MagicIndicatorUtils.OnMagicIndicatorChangeListener, BaseQuickAdapter.OnItemChildLongClickListener, OnRefreshListener {
    @Inject
    PeriodicalInfoPresenter<PeriodicalInfoMvpView> mPresenter;

    private ActivityPeriodicalInfoBinding mBinding;

    private EasyPopup mEasyPopup;
    private SortsBean mSortsBean;//选择的排序实体
    private List<SortsBean> mSortsBenas;//排序列表
    private int mSortsIndex = 1;

    private List<String> mDataList;//选择器文字列表
    private int mSelectIndex = 0;//所选位置

    private FragmentContainerHelper mFramentContainerHelper;
    private List<TimeBean> mTimeBeans;//时间数组


    private static final String BEAN_KEY = "BEAN_KEY";
    private PeriodicalBean mPeriodicalBean;//选择的期刊

    public static Intent getIntent(Context context, PeriodicalBean periodicalBean) {
        Intent intent = new Intent(context, PeriodicalInfoActivity.class);
        intent.putExtra(BEAN_KEY, periodicalBean);
        return intent;
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected void getLayout() {
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_periodical_info);
    }

    @Override
    protected void onDestroy() {
        mPresenter.onDetach();
        super.onDestroy();
    }

    @Override
    protected void initViewAndData() {
        mPresenter.onAttach(this);
        mPeriodicalBean = getIntent().getParcelableExtra(BEAN_KEY);

        if (mPeriodicalBean == null) {
            onError(R.string.error_message);
            return;
        }

        mSortsBenas = new ArrayList<>();
        mSortsBenas.add(new SortsBean(R.string.sorts_one_title, "1"));
        mSortsBenas.add(new SortsBean(R.string.sorts_two_title, "2"));

        mSelectIndex = 1;
        mSortsBean = mSortsBenas.get(mSelectIndex);

        initToolbar();

        initRefreshLayout();

        initRecyclerView();

        initSortsView();

        addDisposable(RxView.clicks(mBinding.toolBar.tvSorts).throttleFirst(1, TimeUnit.SECONDS).subscribe(o -> openSortsView()));
        addDisposable(RxView.clicks(mBinding.toolBar.ivOk).throttleFirst(1, TimeUnit.SECONDS).subscribe(o -> editor(false)));
        addDisposable(RxView.clicks(mBinding.toolBar.tvEditor).throttleFirst(1, TimeUnit.SECONDS).subscribe(o -> editor(true)));
        editor(false);

        mBinding.editorView.setOnEditorListener(new EditorView.OnEditorListener() {
            @Override
            public void onSelectAll(boolean all) {
                mBinding.recyclerView.selectAll(all);
            }

            @Override
            public void onClick(View view) {
                mPresenter.addBook(mBinding.recyclerView.getSelectedData());
                editor(false);
            }
        });

        mBinding.recyclerView.setOnAddListener(bookBean -> mPresenter.addBook(Collections.singletonList(bookBean)));

        mPresenter.getTimeClassList(mPeriodicalBean.getId());
    }

    private void initMagicIndicator() {
        AppIndicatorUtils.initSurroundedMagicIndicator(mContext, null, mBinding.magicIndicator, mDataList, this);
        mFramentContainerHelper = new FragmentContainerHelper(mBinding.magicIndicator);
    }

    private void initToolbar() {
        setToolbar(mBinding.toolBar.toolBar, true);
        mBinding.toolBar.tvTitle.setText(mPeriodicalBean.getName());
    }

    private void initRefreshLayout() {
        SmartRefreshUtils.initRefresh(mContext, mBinding.refreshLayout, this);
    }

    private void initRecyclerView() {
        if (mBinding.recyclerView.getAdapter() != null)
            mBinding.recyclerView.getAdapter().setOnItemChildLongClickListener(this);
        mBinding.recyclerView.setRefreshLayout(mBinding.refreshLayout);
        mBinding.recyclerView.setOnSelectedChangeListener(() -> mBinding.editorView.setNum(mBinding.recyclerView.getSelectedData().size(), EditorView.ADD));
    }

    /**
     * 初始化排序界面
     *
     * @author Chenlei
     * created at 2018/11/14
     **/
    private void initSortsView() {
        mEasyPopup = EasyPopup.create()
                .setContext(this)
                .setContentView(R.layout.view_sorts)
                .setAnimationStyle(R.style.SortsPopAnim)
                .setOnViewListener((view, basePopup) -> {
                    View arrowView = view.findViewById(R.id.arrow_image);
                    arrowView.setBackground(new TriangleDrawable(TriangleDrawable.TOP, ContextCompat.getColor(mContext, R.color.color_937f69)));
                })
                .setFocusAndOutsideEnable(true)
//                .setBackgroundDimEnable(true)
//                .setDimValue(0.5f)
//                .setDimColor(Color.RED)
//                .setDimView(mTitleBar)
                .apply();

        TextView sortsOneBtn = mEasyPopup.findViewById(R.id.sorts_one_btn);
        sortsOneBtn.setText(mSortsBenas.get(0).getStrResId());
        TextView sortsTwoBtn = mEasyPopup.findViewById(R.id.sorts_two_btn);
        sortsTwoBtn.setText(mSortsBenas.get(1).getStrResId());
        addDisposable(RxView.clicks(sortsOneBtn).throttleFirst(1, TimeUnit.SECONDS).subscribe(o -> updateSortsView(mSortsBenas.get(0))));
        addDisposable(RxView.clicks(sortsTwoBtn).throttleFirst(1, TimeUnit.SECONDS).subscribe(o -> updateSortsView(mSortsBenas.get(1))));
    }

    /**
     * 更新排序界面
     *
     * @param sortsBean 更新信息
     */
    private void updateSortsView(SortsBean sortsBean) {
        if (mEasyPopup != null) mEasyPopup.dismiss();
        mSortsBean = sortsBean;
        mBinding.toolBar.tvSorts.setText(sortsBean.getStrResId());
        if (mTimeBeans == null || mTimeBeans.size() <= 0) {
            getBookListSuccess(new ArrayList<>());
            return;
        }
        onRefresh(null);
    }

    /**
     * 打开排序界面
     *
     * @author Chenlei
     * created at 2018/11/14
     **/
    private void openSortsView() {
        mSortsIndex = mSortsIndex == 1 ? 0 : 1;
        updateSortsView(mSortsBenas.get(mSortsIndex));
//        int offsetX = UiUtils.dp2px(mContext, 20) - mBinding.toolBar.tvSorts.getWidth() / 2;
//        mEasyPopup.showAtAnchorView(mBinding.toolBar.toolBar, YGravity.BELOW, XGravity.ALIGN_RIGHT, offsetX, 0);
    }

    /**
     * 更新时间选择
     *
     * @param index 当前选择的时间位置
     */
    @Override
    public void onChange(int index) {
        mFramentContainerHelper.handlePageSelected(index);
        getData(index);
    }

    /**
     * 根据时间位置修改显示信息
     *
     * @param index 时间位置
     */
    private void getData(int index) {
        mSelectIndex = index;
        updateSortsView(mSortsBean);
    }

    /**
     * 长按开启编辑模式
     *
     * @author Chenlei
     * created at 2018/11/14
     **/
    @Override
    public boolean onItemChildLongClick(BaseQuickAdapter adapter, View view, int position) {
        if (mBinding.recyclerView.isEditor()) return false;
        editor(true);
        return false;
    }

    /**
     * 编辑模式界面变化
     *
     * @param editor 是与否
     */
    private void editor(boolean editor) {
        if (editor) {
            mBinding.refreshLayout.finishRefresh();
        }
        mBinding.refreshLayout.setEnableRefresh(!editor);
        mBinding.editorView.setNum(0, EditorView.ADD);
        mBinding.editorView.setVisibility(!editor ? View.GONE : View.VISIBLE);
//        mEditorBtn.setVisibility(editor ? View.GONE : View.VISIBLE);
        mBinding.toolBar.tvSorts.setVisibility(editor ? View.GONE : View.VISIBLE);
        mBinding.toolBar.ivOk.setVisibility(!editor ? View.GONE : View.VISIBLE);
        mBinding.recyclerView.editor(editor);
    }

    @Override
    public void getTimeClassListSuccess(List<TimeBean> timeBeans) {
        mDataList = new ArrayList<>();
        mTimeBeans = timeBeans;
        for (TimeBean timeBean : timeBeans) {
            mDataList.add(timeBean.getName());
        }
        initMagicIndicator();
        initView();
    }

    private void initView() {
        getData(0);
    }


    @Override
    public void getBookListSuccess(List<BookBean> bookBeans) {
        mBinding.recyclerView.setData(bookBeans);
    }

    @Override
    public void getBookListFailed() {
        mBinding.recyclerView.firstLoadFailed();
    }

    @Override
    public void activityOnEvent(EventCenter eventCenter) {
        super.activityOnEvent(eventCenter);
        switch (eventCenter.getEventCode()) {
            case EventCode.ADD_BOOK_SUCCESS:
                if (mPresenter == null) return;
                updateSortsView(mSortsBean);
                break;
        }
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        if (mTimeBeans == null || mTimeBeans.size() <= 0 || mSortsBean == null) {
            refreshlayout.finishRefresh();
            return;
        }
        mPresenter.getBookList(mPeriodicalBean, mSortsBean, mTimeBeans.get(mSelectIndex).getId());
    }
}
